package vertx;

import org.vertx.java.core.Handler;
import org.vertx.java.core.Vertx;
import org.vertx.java.core.eventbus.EventBus;
import org.vertx.java.core.eventbus.Message;
import org.vertx.java.core.http.HttpServerRequest;
import org.vertx.java.core.http.RouteMatcher;
import org.vertx.java.core.json.JsonObject;
import org.vertx.java.core.logging.Logger;
import org.vertx.java.platform.Verticle;

public class Route extends Verticle {
	
	// Create a route matcher for the HTTP server
	private RouteMatcher rm = null;
	// Event bus from ServerHttp
//	private EventBus eb = null;
	// Object for logger
	Logger logger = null;

	public Route(Vertx vertx, EventBus eb, Logger logger) {
		this.rm = new RouteMatcher();
//		this.eb = eb;
		this.logger = logger;

		final EventBus feb = eb;
		
		// Extract the params from the uri
		rm.get("/tag/:tag", new Handler<HttpServerRequest>() {
            public void handle(HttpServerRequest req) {
            	final HttpServerRequest request = req;
            	final String tag = req.params().get("tag");
            	feb.send("webclient_address", tag, new Handler<Message>() {
                    public void handle(Message message) {
                    	message.body();

                    	// The webclient has returned a message!
//                    	var items = JSON.parse(message).items;
                    	
                    	String html = "<html><body><h1>Results for " + tag + "</h1>";
//                    	for (var i = 0; i < items.length; i++) {
//                    		html += "<h3>" + items[i].title + "</h3>";
//                    		html += "<a href="" + items[i].link + ""><img src="" + items[i].media.m + "" /></a>";
//                    		html += items[i].description;
//                    	}
                    	html += "</body></html>";
                    	request.response().end(html);
                    }
                });
            }
            	
       	});
		
	}

//	public String get(String url) {
//		
//	}
	
	public void getWithRegEx() {
		// Default route responds with an error message
//		rm.getWithRegEx(".*", function(req) {
//			req.response.end("ERROR: fill the tag");
//		});
	}
	
}
